<?php
/**
 * +----------------------------------------------------------------------
 * | 九月科技-ztuc.cn
 * +----------------------------------------------------------------------
 *                      .::::.
 *                    .::::::::.            | AUTHOR: siyu
 *                    :::::::::::           | EMAIL: ztucke@ztuc.cn
 *                 ..:::::::::::'           | DATETIME: 2020/01/31
 *             '::::::::::::'
 *                .::::::::::
 *           '::::::::::::::..
 *                ..::::::::::::.
 *              ``::::::::::::::::
 *               ::::``:::::::::'        .:::.
 *              ::::'   ':::::'       .::::::::.
 *            .::::'      ::::     .:::::::'::::.
 *           .:::'       :::::  .:::::::::' ':::::.
 *          .::'        :::::.:::::::::'      ':::::.
 *         .::'         ::::::::::::::'         ``::::.
 *     ...:::           ::::::::::::'              ``::.
 *   ```` ':.          ':::::::::'                  ::::..
 *                      '.:::::'                    ':'````..
 * +----------------------------------------------------------------------
 */
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/10
 * Time: 21:59
 */

namespace app\store\model;

use think\facade\Db;
use app\store\controller\Upload;
use app\store\model\core\InitModel;
use app\store\model\UserBlack;
use think\model\concern\SoftDelete;

/**
 * 文章
 * Class Article
 * @package app\model\admin
 */
class Article extends InitModel
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;
    // 定义表
    protected $name = 'article';

    // 第一自动写入时间字段
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 可用字段
    protected static $available = [
        'id',
        'cat_id',
        'title',
        'content',
        'types',
        'flag',
        'view',
        'click',
        'weigh',
        'create_time',
        'update_time',
        'status',
    ];

    // 栏目类型,声明int类型
    public static function flag($flag)
    {
        switch ($flag) {
            case 1:
                return $flag = 1;
                break;
            case 2:
                return $flag = 2;
                break;
            case 3:
                return $flag = 3;
                break;
            default:
                return $flag = '未知';
        }
    }


    /**
     * 新增
     * @param $post
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: MK
     * @Time: 2020/4/10 23:16
     */
    public static function add($post)
    {
        try {
            if (isset($post['id'])) unset($post['id']);

            if (!$post) return false;
            $model = new Article();
            $model->allowField(self::$available)->save($post);

            // 获取自增id
            $tableId = $model->id;
            //保存图片
            if (!empty($post['image'])) {
                Image::create([
                    'table_id' => $tableId,
                    'url' => $post['image'],
                    'types' => Upload::TYPE_ARTICLE,
                    'file_size' => $post['filesize'],
                    'mine' => $post['mine']
             ]);
            }
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

public static function getBase()
{ 
    $list = Article::order(['id'=>'desc'])->where(['status' => 1])->where(['cat_id' => mt_rand(1,19)])->paginate(['list_rows' => 15, 'query' => request()->param()]);   
     if (!empty($list)){
            // 获取图片
            foreach ($list as $k=>$v){
                 if (!empty($v['id'])){
                $list[$k]['image'] = Image::image($v['id'],Upload::TYPE_ARTICLE);
                 }
             }
         }
    $data = Article::order(['id'=>'desc'])->where(['status' => 1])->where(['cat_id' => mt_rand(1,19)])->limit(20)->select();
        
            return $model = ['list' => $list, 'data' => $data];
  }
    /**
     * 前端展示
     * @param int $id->orderRaw("rand()")
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     * @author: MK
     * @Time: 2020/4/13 21:34
     */
    public static function getArticle($id, $current_page, $current_limit)
    {    if ($current_limit > 500) return false;
        $data = Article::order(['weigh'=>'desc','id'=>'desc'])->where(['status' => 1, 'cat_id' => $id])
            ->force('idx_status')
            ->order('create_time', 'desc')
            ->paginate(['list_rows' => $current_limit??12, 'query' => request()->param()])
            ->each(function ($item, $key) {
                $item['image'] = Image::image($item['id'], Upload::TYPE_ARTICLE);
                $data = self::flag($item['flag']);
                $item['flag'] = $data == 1 ? '<span class="layui-btn layui-btn-xs">最新</span>' : ($data == 2 ? '<span class="layui-btn layui-bg-red layui-btn-xs">热门</span>' : ($data == 3 ? '<span class="layui-btn layui-bg-orange layui-btn-xs">推荐</span>' : '<span class="layui-btn layui-bg-orange layui-btn-xs">未知</span>'));  
                $love = Article::where(['weigh' => $item['weigh']])->value('weigh');
                $item['weigh'] =  $love == 1 ? '<span class="layui-btn layui-btn-primary layui-border-red layui-btn-xs">置顶</span>' : '';
                $count = Notice::where('article_id', $item['id'])->count();
                $item['count'] = isset($count)?$count:0;
                return $item;
            });
             $count = Article::order(['weigh'=>'desc','id'=>'desc'])->where(['status' => 1, 'cat_id' => $id])->count();
             $data  = [
                'current_id' => $id,
                'current_page' => $current_page,
                'current_limit' => $current_limit,
                'count' => $count,
                'data'  => $data,
            ];
           return $data;
    }

    /**
     * 浏览+1
     * @param int $id
     * @return bool
     * @author: MK
     * @Time: 2020/4/12 21:54
     */
    public static function view($id, $user_id, $user_ip)
    {
        //判断帖子id是否存在
        $model = Article::find($id);
        
        if (!empty($model->id)) {
            //更新浏览
            Article::update(['view' => Db::raw('view+1')], ['id' => $id]);
            //组装数据
             $map = [
            'name' => \app\store\controller\Index::cars()['car'],
            'user_id' => $user_id,
            'ip' => $user_ip,
            'article_id' => $id,
            'view' => Db::raw('view+1'),
            'url' => request()->url(),
            'agent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
        ]; 
             //查询今天帖子是否存在
            $model = ArticleLog::whereTime('create_time', 'today')->where(['article_id' => $id])->find();
            
        if(!empty($model)) 
        {
            //存在更新数据
        ArticleLog::whereTime('create_time', 'today')->where(['article_id' => $id])->update(['view' => Db::raw('view+1')]);
        
         }else{   
             //不存在就插入
       ArticleLog::create($map);
        
         }
        }
        return true;
    }

    /**
     * 详情
     * @param $id
     * @return array|null|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: MK
     * @Time: 2020/4/12 18:08
     */
    public static function findArticle($id)
    {
        $list = Article::where(['status' => 1, 'id' => $id])->find();
     // 获取用户信息
                if (!empty($list['cat_id'])){
                    $list['cat_name'] = Navbar::findNavbar($list['cat_id'])['cat_name'];
                    $list['image'] = Image::image($list['id'], Upload::TYPE_ARTICLE);
                     }
           return $list;

    }
    // 上一页
    public static function minCode($id)
    {
        return Article::where('cat_id',$id)->min('id');
    }

    // 下一页
    public static function maxCode($id)
    {
        return Article::where('cat_id',$id)->max('id');
    }

    // 上一篇
    public static function lastCode($id, $uid)
    {
        return Article::order('id desc')->where(['status' => 1, 'cat_id' => $uid])
            ->where('id', '<', $id)->limit(0, 2)->find();
    }

    // 下一篇
    public static function nextCode($id, $uid)
    {
        return Article::order('id asc')->where(['status' => 1, 'cat_id' => $uid])
            ->where('id', '>', $id)->limit(0, 2)->find();
    }

    /**
     * 点赞
     * @param int $uid
     * @param int $id
     * @return bool
     * @author: MK
     * @Time: 2020/4/12 22:02
     */
    public static function click($user_id, $article_id, $user_ip)
    {

        $map = [
            'user_id' => $user_id,
            'article_id' => $article_id,
            'ip' => $user_ip,
        ];
        $where = ['article_id' => $map['article_id'], 'user_id' => $map['user_id'], 'ip' => $map['ip']];
        $log = ClickLog::where($where)
            ->whereTime('create_time', 'today')
            ->force('click_force')// 强制索引
            ->lock(true)// 数据库锁，防止多人同时点击出错
            ->count();
        if ($log >= 1) return false;
        
        Article::update(['click' => Db::raw('click+1')], ['id' => $article_id]);
        ClickLog::add($map);
        return true;
    }
}